Ploty Package - An Introduction

Introduction

Today, we will cover the “plotly” package and explore it using a variety of datasets. First, we will start by uploading the packages that will be needed today. If these packages do not load, be sure to install them.

Functions

This package can be used in a variety of ways to make data interactive and fun. The functions we will be exploring today are: 1. add surface 2. plot_ly 3. animation 4. add trace 5. colorbar 6. layout 7. add image

library(plotly)
library(tidyverse)
library(here)
library(readr)
library(maps)
library(dplyr)
library(ggplot2)
library(lubridate)
library(purrr) #Used to  create the animation frames
library(rmdformats)
library(heatmaply)
library(palmerpenguins)
library(reticulate)

3D Chart Example

Load Data

CherryTree_Data_ <- read_csv(here("Data/CherryTree Data .csv"))

Change to a numeric matrix

CherryTree <- as.matrix(CherryTree_Data_) # change the data set to a numeric matrix 

Plot numeric matrix

fig <- plot_ly(z = ~CherryTree) # plot by numeric matrix 
fig<- fig %>% add_surface()

View figure

fig 

An example of an animation timeseries

data("economics")

Mutate Data

econ <- economics %>%
  mutate(cumulative_pop = cumsum(pop))

Create a filled area plot with an animation frame

econ %>%
  plot_ly(x = ~date, 
          y = ~cumulative_pop, 
          fill = ~pop,
          type = "scatter", 
          mode = "none",
          stackgroup = "one",
          animation_frame = ~year(date)) %>%
    add_trace(y = ~0, 
              hoverinfo = "skip", 
              showlegend = FALSE) %>%
    layout(title = "US Population Over Time",
           xaxis = list(title = "Date"),
           yaxis = list(title = "Cumulative Population")) %>%
    colorbar(title = "Population", len = 0.5, y = 0.8, ypad = 0)

Our goal is to look at the median population data for the state of California from 2000 and 2010. Note: Plotly has built-in Country and State Geometries.

Now let’s explore another graph type with this package. We will create a scatter plot with this data to create interactive points.

Load Data

chemicaldata <- read_csv(here("Data/chemicaldata.csv"))

Create a scatter mapbox plot with the latitude and longitude data

fig <- plot_ly(chemicaldata, type = "scattermapbox",
                             mode = "markers", 
                             marker = list(size = 10, 
                                           color = "red"), 
                                           lon = ~Long, lat = ~Lat)

Set the map layout

fig <- fig %>% layout(mapbox = list(center = list(lon = -157.763, 
                                                  lat = 21.274),
                                                  zoom = 15, 
                                                  style = "open-street-map"))

Show the map

fig # Show the map

Histogram example using Hobbs data

plot_ly( 
  data = hobbs, 
  alpha = 0.6, 
  x = ~t, 
  y = ~nms, 
  type = "histogram") %>% 
  layout(title = "A Measure of Hobbs Data")

Heatmap example using penguin data (need to make more edits)

penguinplot <- as.matrix(penguins_raw)

fig<- plot_ly(z = ~penguinplot, type = "heatmap")

View Plot

fig

Bar Chart

Load Data

data("msleep")

Create bar plot

sleep_bar <-msleep %>%
             plot_ly(x = ~order, 
                     y = ~sleep_rem,
                     type = "bar", 
                     name = "REM Sleep")

Add layout information

sleep_bar <- sleep_bar %>% 
  layout(title = "Average REM Sleep by Order", 
         xaxis = list(title = "Animal Order"), 
         yaxis = list(title = "REM Sleep (hours)"))

Show plot

sleep_bar

THINK, PAIR, AND SHARE

Can you create a similar graph but show the average REM sleep by each genus?

# Load Data
data(msleep)

Assinging a Data Set

msleep <- ggplot2::msleep %>% # we need to assign the data set "msleep" found in ggplot and assign it to our current RMarkdown.
  rename(`Type of Diet` = vore, `Total Hours of Sleep` = sleep_total) %>% #changes names before making graph so axis doesn't need to be changed later
  na.omit() #removes any incomplete or N/A data from data set

Create a bar graph

Q <- msleep %>% # We have assigned our graph the letter Q to request it easily later
  plot_ly(x = ~reorder(`Type of Diet`, -`Total Hours of Sleep`), 
          y = ~`Total Hours of Sleep`, # changing the order of how the bars show up so they're increasing in hours of sleep.
          type = 'bar', # type of graph
          marker = list(color = rainbow(nrow(msleep), #uses rainbow colors for bars indicating their sleeping hours individually and as a dietary group.
                        alpha = 0.7))) %>% #determines the transparency/opacity of the bars 0.0 being completely transparent
  
  
  layout(xaxis = list(title = "Type of Diet"), #naming x-axis
         yaxis = list(title = "Total Hours of Sleep"), #naming y-axis
         title = "Total Hours of Sleep vs. Type of Diet") #naming graph

Animating your Graph

# Add animation to the bars
Q <- Q %>% 
  animation_opts(frame = 100, easing = 'elastic') #controls timing and style of animation,

Displaying our Results

# Display the graph
Q

Additonal Resources